package day13;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author oldliu
 * @since 1.0
 */
public class AdvanceServer {
    public static void main(String[] args) {
        ExecutorService es= Executors.newFixedThreadPool(10);
        try {
            ServerSocket st=new ServerSocket(9999);
            System.out.println("Server start...");
            while (true){
                Socket s = st.accept();
                es.submit(new ObjectThread(s));
                //es.submit(new SendThread(s));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class SendThread implements Callable<Boolean>{
    private final Socket s;
    final static String Folder="E:\\java_workspace\\hbuilderproj\\java61\\images";
    public SendThread(Socket s){
        this.s=s;
    }
    @Override
    public Boolean call() throws Exception {
        System.out.println(s+"连上了。。。。");
        try {
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            //你们告诉我要哪个文件名，，我把相应的文件发给你
            BufferedReader br=new BufferedReader(new InputStreamReader(in));
            String fileName = br.readLine();
            FileInputStream fin=new FileInputStream(new File(Folder,fileName));
            byte[] b=new byte[fin.available()];
            fin.read(b);
            fin.close();
            out.write(b);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            s.close();
        }
        return  false;
    }
}

class ObjectThread implements Runnable{
    private final Socket s;

    static Map<String,String> map=new HashMap<>();
    static{
        map.put("taller","刘贵横");
        map.put("ai","laoliu");
        map.put("handsome","张国栋");
        map.put("pretty","小徐");
    }
    public ObjectThread(Socket s){
        this.s=s;
    }
    @Override
    public void run() {
        try {
            //InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            ObjectOutputStream oout=new ObjectOutputStream(out);
            oout.writeObject(map);
            oout.reset();

        }catch (Exception e){

        }finally {
            try {
                s.close();
            } catch (Exception e) {

            }
        }
    }
}